# 工作区视图（继承QGraphicsView）
from PyQt5.QtWidgets import QGraphicsView, QGraphicsScene
from PyQt5.QtCore import Qt, QRect
from PyQt5.QtGui import QPainter, QPen, QBrush, QColor


class WorkareaView(QGraphicsView):
    """可视化工作区视图，承载画布和交互"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.zoom_factor = 1.0
        self.init_ui()
        self.init_grid()

    def init_ui(self):
        # 创建场景
        self.scene = QGraphicsScene()
        self.setScene(self.scene)

        # 视图配置
        self.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setBackgroundBrush(QBrush(Qt.white))

        # 设置场景尺寸
        self.scene.setSceneRect(-500, -500, 1000, 1000)

    def init_grid(self):
        """初始化网格背景"""
        self.grid_pen = QPen(QColor(220, 220, 220), 1, Qt.DashLine)
        self.grid_step = 20  # 网格间隔

    def drawBackground(self, painter, rect):
        """重写背景绘制方法"""
        super().drawBackground(painter, rect)

        # 绘制网格
        left = int(rect.left()) - (int(rect.left()) % self.grid_step)
        top = int(rect.top()) - (int(rect.top()) % self.grid_step)
        right = int(rect.right())
        bottom = int(rect.bottom())

        painter.setPen(self.grid_pen)
        # 绘制垂直线
        for x in range(left, right, self.grid_step):
            painter.drawLine(x, top, x, bottom)
        # 绘制水平线
        for y in range(top, bottom, self.grid_step):
            painter.drawLine(left, y, right, y)

    def wheelEvent(self, event):
        """滚轮缩放（基础实现）"""
        zoom_rate = 1.001  **  event.angleDelta().y()
        self.scale(zoom_rate, zoom_rate)